<?php
class WbController extends DomController {

	private $selectedSiteId;
	
	public function index() {
		
	}
	
	public function pages() {
		$this->auth('manageSites');
		if( $_GET['delete'] && $item = WbSite::load( $_GET['delete'] )){
			$item->delete();
		}
						
		$source = new DomArDataSource( WbSite::query()->where('t.className=\'WbSite\'')->orderBy('t.name DESC'), 40 );
		
		$panel = array(
			'title' => 'Lehed',
			'layout' => 'table',
			'layoutConfig' => array(
				'columns' => 1,
			),
			'items' => array(
				array(
					'type' => 'button',
					'title' => 'Lisa uus leht',
					'link' => $this->getUrl('newSite/'),
				),
				array(
					'type' => 'grid',
					'source' => $source,
					'fields' => array(
						array('key' => 'name', 'title' => 'Nimi'),
						array('type' => 'gridButton', 'value' => 'Muuda', 'link' => $this->getUrl('page/'), 'title' => 'Valikud','colspan' => 2),
						array('type' => 'gridButton', 'value' => 'Kustuta', 'link' => $this->getUrl('pages/&delete='), 'confirmMessage' => 'Olete kindel, et soovite kustutada?' ),
					),
				),
			),
		);
					
		$this->view->contents = DomFg::render( $panel );
	}
	
	public function newPage( $parentId ) {

		$parent = DomAr::load( $parentId, 'WbPage');
		
		$post = DomFgPost::getInstance();
		if( $post->save ) {
			
			$item = new $post->type;
			$this->_updatePage( $item );
			
			if( $item->save() ) {
				$this->goToSection('page/'.$item->id);
			} else {
				$message = array('message' => 'Tekkinud on viga!','type' => 'ok','colspan' => 2,'description' => implode('<br>',$item->getValidationReport()->messages),);
			}
		}
				
		$panel = array(
			'title' => 'Uus lehekülg',
			'layout' => 'table',
			'style' => 'width:500px',
			'action' => $this->getUrl('newPage/'.$parentId),
			'layoutConfig' => array(
				'columns' => 2,
				'columnWidths' => array( 150 ),
			),
			'items' => array(
				$message ,
				array(
					'type' => 'textField',
					'title' => 'Nimi',
					'value' => $item->name,
					'name' => 'name',
				),
				array(
					'type' => 'select',
					'title' => 'Ülemleht',
					'values' => $parent->getRoot()->getTreeArray(),
					'selected' => $parentId,
					'name' => 'parent',
				),
				array(
					'type' => 'select',
					'title' => 'Tüüp',
					'values' => Wb::getAddableModules(),
					'name' => 'type',
				),
			),
			'buttons' => array(
				array(
					'title' => 'Salvesta',
					'name' => 'save'
				),
			),
		);
				
		$this->view->contents = DomFg::render( $panel );
	
	}
	
	public function newSite() {
		$this->auth('manageSites');
		
		$post = DomFgPost::getInstance();
		if( $post->save ) {
			
			$item = new WbSite();
			$item->name = $post->name;
			
			if( $item->save() ) {
				$this->goToSection('page/'.$item->id);
			} else {
				$message = array('message' => 'Tekkinud on viga!','type' => 'ok','colspan' => 2,'description' => implode('<br>',$item->getValidationReport()->messages),);
			}
		}
				
		$panel = array(
			'title' => 'Uus leht',
			'layout' => 'table',
			'action' => $this->getUrl('newSite/'.$id),
			'layoutConfig' => array(
				'columns' => 2,
				'columnWidths' => array( 150 ),
			),
			'items' => array(
				$message ,
				array(
					'type' => 'textField',
					'title' => 'Nimi',
					'value' => $item->name,
					'name' => 'name',
				),
			),
			'buttons' => array(
				array(
					'title' => 'Salvesta',
					'name' => 'save'
				),
			),
		);
				
		$this->view->contents = DomFg::render( $panel );
	
	}

	
	
	public function _updatePage( WbPage $item ) {
		if( $_GET['delete'] && $item = DomAr::load( $_GET['delete'], 'WbPage' )){
			$item->delete();
		}
		
		$post = DomFgPost::getInstance();
		if( $post->save ) {
				
			$item->name = $post->name;
			$item->active = (bool)$post->active;
			$item->urlKey = $post->urlKey ? $post->urlKey : NULL;
			$item->template = $post->template;
			
			$item->metaTitle = $post->metaTitle;
			$item->metaDescription = $post->metaDescription;
			$item->metaKeywords = $post->metaKeywords;
			
			if( $item instanceof WbSite ) {
				$item->isMainSite = (bool)$post->isMainSite;
			} else {
				$item->isFrontPage = (bool)$post->isFrontPage;
			}
			
			$parent = DomAr::load( $post->parent, 'WbPage');
			if( $parent && $parent->id != $item->id && $parent->isParentOf($item) == false ) {
				$item->parent = DomAr::load( $post->parent, 'WbPage');
			}
			
			foreach( $item->pages as $page ) {
				if( $post->pagesOrder[$page->id] !== NULL ) {
					$page->order= $post->pagesOrder[$page->id];
				}
			}
		}
	}
	
	public function _getPageItems(WbPage $item ) {

		return array(
			array(
				'type' => 'value',
				'title' => 'Tüüp',
				'value' => Wb::getModuleName( get_class($item)),
			),
			array(
				'type' => 'textField',
				'title' => 'Nimi',
				'value' => $item->name,
				'name' => 'name',
				'style' => 'width:400px',
			),
			array(
				'type' => 'checkBox',
				'title' => 'Aktiivne',
				'checked' => $item->active,
				'name' => 'active',
			),
			($item instanceof WbSite ? array(
				'type' => 'checkBox',
				'title' => 'Esileht',
				'checked' => $item->isMainSite,
				'name' => 'isMainSite',
			) : array(
				'type' => 'checkBox',
				'title' => 'Esileht',
				'checked' => $item->isFrontPage,
				'name' => 'isFrontPage',
			)),
			($item instanceof WbSite ? null : array(
				'type' => 'select',
				'title' => 'Ülemleht',
				'values' => $item->getRoot()->getTreeArray(),
				'selected' => $item->parent->id,
				'name' => 'parent',
			)),
			array(
				'type' => 'select',
				'title' => 'Kujundus',
				'values' => $item->getTemplates(),
				'selected' => $item->template,
				'name' => 'template',
			),
		);
	}
	
	public function _getPagePanels( WbPage $item) {
		
		function handler_order( $row, $i ) {
			$field  = array(
				'type' => 'number',	
				'value' => $row->order->pos,
				'name' => 'pagesOrder['.$row->id.']',
			);
			return DomFg::render( $field );
		}
		
		function moduleName( $row ) {
			return Wb::getModuleName( get_class($row) );
		}
		$pagesTab = array(
			'type' => 'panel',
			'title' => 'Alamlehed',
			'layout' => 'table',
			'layoutConfig' => array(
				'columns' => 1,
				'columnWidths' => array(),
			),
			'items' => array(
				array(
					'type' => 'button',
					'title' => 'Lisa uus alamleht',
					'link' => $this->getUrl('newPage/'.$item->id),
				),
				array(
					'type' => 'grid',
					'source' => new DomArDataSource( $item->pages->query()->orderBy('t.order'), 10000 ),
					'fields' => array(
						array('key' => 'name', 'title' => 'Nimi'),
						array('handler' => 'moduleName', 'title' => 'Tüüp', 'width' => 130,),
						array('handler' => 'handler_order', 'title' => 'Jrk', 'width' => 80,),
						array('type' => 'gridButton', 'value' => 'Muuda', 'link' => $this->getUrl('page/'), 'title' => 'Valikud','colspan' => 2, 'width' => 60),
						array('type' => 'gridButton', 'value' => 'Kustuta', 'link' => $this->getUrl('page/'.$item->id.'/&delete='), 'confirmMessage' => 'Olete kindel, et soovite kustutada lehe koos tema alamlehtedega.', 'width' => 60 ),
					),
				),
			),
		);
		$metaTab = array(
			'type' => 'panel',
			'title' => 'Meta info',
			'layout' => 'table',
			'layoutConfig' => array(
				'columns' => 2,
				'columnWidths' => array(150,),
			),
			'items' => array(
				array(
					'type' => 'textField',
					'name' => 'urlKey',
					'value' => $item->urlKey,
					'title' => 'Url tunnus',
					'style' => 'width:500px',
				),
				array(
					'type' => 'textField',
					'name' => 'metaTitle',
					'value' => $item->metaTitle,
					'title' => 'Meta pealkiri',
					'style' => 'width:500px',
				),
				array(
					'type' => 'textArea',
					'name' => 'metaDescription',
					'value' => $item->metaDescription,
					'title' => 'Meta kirjeldus',
					'style' => 'width:500px',
				),
				array(
					'type' => 'textArea',
					'name' => 'metaKeywords',
					'value' => $item->metaKeywords,
					'title' => 'Meta võtmesõnad',
					'style' => 'width:500px',
				),
			),
		);
		return array(
			$pagesTab,
			$metaTab
		);
	}
	
	public function page( $id ) {
		$page = DomAr::load( $id, 'WbPage');
		$controller = $this->loadController(get_class($page));
		if( $controller ) {
			$controller->page( $id );
		} else {
			$this->view->contents = DomFg::render(array(
				'type' => 'panel',
				'style' => 'width:400px',
				'items' => array(
					array(
						'type' => 'error',
						'message' => 'Missing module handler',
					)
				)
			));
		}
	}
	
	
	
	public function _renderSiteTree( WbSite $site, WbPage $selected ) {

		function generateTreeSource( DomController $controller, WbPage $selected, $parentId, $parentNode = NULL ) {
			
			$query = WbPage::query()
				->where('t.parent = '.(int)$parentId )
				->orderBy('t.order');

			foreach( $query->commit() as $element ) {
				$node = new DomFgTreeNode( $element->active ? $element->name : '<span style="color:rgb(170,170,170)">'.$element->name.'</span>' );
				generateTreeSource( $controller, $selected, $element->id, $node );
				$node->link( $controller->getUrl('page/'.$element->id ) );
				$node->icon($element->getTreeIcon());
				if( $element->id == $selected->id ) {
					$node->selected(true);
				}
				$parentNode->add( $node );
			}
		}
		
		$node = new DomFgTreeNode( $site->name );
		$node->icon($site->getTreeIcon());
		$node->link( $this->getUrl('page/'.$site->id ) );
		if( $site->id == $selected->id ) {
			$node->selected(true);
		}
		generateTreeSource( $this, $selected, $site->id, $node );
		
		$panel = array(
			'title' => 'Lehe puu',
			'layout' => 'table',
			'style' => 'width:200px; height:1000px; float:left; position:relative; top:-10px;',
			'layoutConfig' => array(
				'columns' => 1,
			),
			'items' => array(
				array(
					'id' => 'siteTree',
					'type' => 'tree',
					'source' => array($node),
				),
			),
		);
		$this->view->tree = DomFg::render( $panel );
	}
	
	public function getMenuLinks() {
		$list = array();
		if( $this->getUser()->rights->isAllowed('manageSites') ) {
			$list[] = array(
				'title' => 'Veebilehed',
				'link' => $this->getUrl('pages/'),
			);
		}
		foreach( DomSql::selectQuery('SELECT id,name FROM '.WbSite::getDbTable().' WHERE className=\'WbSite\' ORDER BY name') as $site ) {
			$list[] = array(
				'title' => $site['name'],
				'link' => $this->getUrl('page/'.$site['id']),
			);
		}
		return $list;
	}
	
	

}